﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FeedbackNetwork.network
{
    class Node
    {
        public float loss = 0f;
        public float[] w;
        public float b;
        public float lr=0.0001f;
        private FloatTensor input;
        
        public Node(int input_size)
        {
            this.SetSize(input_size);
        }

        public Node()
        {

        }

        public void InitW(float s)
        {
            for (int i = 0; i < this.w.Length; i++)
                this.w[i] = s;
        }

        public void InitB(float s)
        {
            this.b = s;
        }



        public void SetSize(int input_size)
        {
            this.w = new float[input_size];
        }

        public FloatTensor Forward(FloatTensor input)
        {
            if (float.IsNaN(input.Sum()))
                Console.WriteLine("NAN出现了");
            this.input = new FloatTensor(input);
            FloatTensor temp = new FloatTensor(this.w, new int[] { this.w.Length, 1 });
            FloatTensor resu  = input.MatrixMul(temp);
            return resu.Add(this.b);
            
        }

        public FloatTensor Backward(FloatTensor input)
        {
            FloatTensor temp = new FloatTensor(this.w, new int[] { 1, this.w.Length });
            FloatTensor result = input.MatrixMul(temp);

            float mean_back = input.Sum() / input.GetDimensionShape(0);
            float mean_forward = this.input.Sum() / this.input.GetDimensionShape(0);

            for(int i = 0; i < this.w.Length; i++)
            {
                this.w[i] -= mean_back * this.lr * mean_forward;
                
            }

            this.b -= this.lr * mean_back;
            return result;
        }

        public void SetLearnRate(float lr)
        {
            this.lr = lr;
        }
    }
}
